<?php

namespace App\Cola\Logic;

use App\Cola\Model\ColaBill;
use App\Cola\Model\ColaTradeCate;
use App\Cola\Service\ColaLedgerService;
use App\Common\Excel;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class ColaImportBill
{

    protected string $file = '';
    protected int $pay_source = 0;
    protected int $user_id = 0;
    protected int $ledger_id = 0;


    /**
     * 处理数据
     * */
    public function example($task_id, $user_id,$leger_id, $pay_source, $file)
    {
        logger()->info('[账单同步]开始', ['user_id' => $user_id, 'pay_source' => $pay_source, 'file' => $file]);
        $redisKey = "bill_import_task:$task_id";

        $this->user_id = $user_id;
        $this->ledger_id = $leger_id;
        $this->pay_source = $pay_source;
        $this->file = $file;
        switch ($pay_source) {
            case ColaBill::PAY_SOURCE_ALIPAY:
                $result = $this->alipayBill();
                break;
            case ColaBill::PAY_SOURCE_WECHAT:
                $result = $this->wechatBill();
                break;
            default:
                $result = false;
//                cache()->set($redisKey, ['code' => 3, 'msg' => '无效的支付来源']); // 设置状态为成功
                logger()->error('[账单同步]无效的支付来源', ['task_id' => $task_id, 'user_id' => $user_id, 'pay_source' => $pay_source]);
                break;
        }
        // 处理导入结果
        if ($result) {
            // 修改任务状态为成功
//            cache()->set($redisKey, ['code' => 2, 'msg' => '导入成功']); // 设置状态为成功
            // 导入成功，处理成功逻辑
            logger()->info('[账单同步]成功', ['user_id' => $user_id, 'pay_source' => $pay_source, 'file' => $file]);
        } else {
            // 导入失败，处理失败逻辑
            logger()->error('[账单同步]失败', ['user_id' => $user_id, 'pay_source' => $pay_source, 'file' => $file]);
        }

        logger()->info('[账单同步]结束', ['user_id' => $user_id, 'pay_source' => $pay_source, 'file' => $file]);
        return $result;
    }

    /**
     * @var ColaLedgerService
     */
    #[Inject]
    protected ColaLedgerService $ledgerService;



    /**
     * 支付宝订单同步
     * 交易时间    交易分类    交易对方    对方账号    商品说明    收/支    金额    收/付款方式    交易状态    交易订单号    商家订单号    备注
     *
     * */
    public function alipayBill()
    {
        $columns = [
            'pay_time' => 'A',
            'trade_cate_id' => 'B',
            'counterparty' => 'C',
            'counterparty_account' => 'D',
            'goods' => 'E',
            'cash_flow' => 'F',
            'money' => 'G',
            'payment_method' => 'H',
            'trade_status' => 'I',
            'trade_sn' => 'J',
            'trade_store_sn' => 'K',
            'remark' => 'L',
        ];

        $cola_list = Excel::readExcel($this->file, $columns, 26);

        if (empty($cola_list)) {
            logger()->info('[账单同步]文件为空', ['pay_source' => $this->pay_source, 'file' => $this->file]);
            return false;
        }
        $trade_cate_list = ColaTradeCate::query()->pluck('id', 'name');

        $insert_data = [];
        foreach ($cola_list as $key => $value) {
            $cash_flow_arr = ['收入' => 1, '支出' => 2, '不计收支' => 3];
            $cash_flow = $cash_flow_arr[$value['cash_flow']];
            if (in_array($value['payment_method'], ['退款成功', '交易关闭'])) {
                $cash_flow = 1;
            }
            //其他
            $trade_cate_id = !empty($trade_cate_list[$value['trade_cate_id']])
                ?$trade_cate_list[$value['trade_cate_id']]
                : 29;

            $insert_data[] = [
                'user_id' => $this->user_id,
                'pay_source' => $this->pay_source,
                'pay_time' => $value['pay_time'],
                'trade_cate_id' => $trade_cate_id,
                'counterparty' => $value['counterparty'],
                'counterparty_account' => $value['counterparty_account'],
                'goods' => $value['goods'],
                'cash_flow' => $cash_flow,
                'money' => $value['money'],
                'payment_method' => $value['payment_method'],
                'trade_status' => $value['trade_status'],
                'trade_sn' => $value['trade_sn'],
                'trade_store_sn' => $value['trade_store_sn'],
                'remark' => $value['remark'],
            ];
        }

        return $this->insertData($insert_data);
    }


    private function insertData(array $insert_data)
    {
        $model = new ColaBill();

        Db::beginTransaction();
        try {
            $insert_data = array_reverse($insert_data);
            $insert_data_chunks = array_chunk($insert_data, 1000);

            $inserted_ids = [];

            foreach ($insert_data_chunks as $chunk) {
                // 批量插入数据并获取插入的ID
                Db::table($model->getTable())->insert($chunk);

                // 获取插入后的ID列表
                $ids = Db::table($model->getTable())
                    ->where('user_id', $this->user_id)
                    ->whereIn('pay_time', array_column($chunk, 'pay_time'))
                    ->pluck('id')
                    ->toArray();

                // 将获取的ID添加到插入ID数组中
                foreach ($ids as $id) {
                    $inserted_ids[] = $id;
                }
            }

            // 插入数据后批量同步到账本
            foreach ($inserted_ids as $inserted_id) {
                $this->ledgerService->JoinBillService($this->user_id, $this->ledger_id, $inserted_id);
            }

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            logger()->error('[账单同步]插入数据库错误', [
                'exception' => exception_to_array($exception),
                'insert_data' => $insert_data,
            ]);
            return false;
        }

        return true;
    }


}